package ch.bfh.java.directorysynchronizer.presentation.actionlisteners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import ch.bfh.java.directorysynchronizer.business.DirectorySynchronizeException;
import ch.bfh.java.directorysynchronizer.business.DirectorySynchronizer;
import ch.bfh.java.directorysynchronizer.presentation.items.TextAreaAppender;
import ch.bfh.java.directorysynchronizer.presentation.items.Workbench;

public class StartSynchronizeButtonListener implements ActionListener
{

	private Workbench workbench;

	public StartSynchronizeButtonListener(Workbench wb)
	{
		this.workbench = wb;
		TextAreaAppender.setTextArea(workbench.getLogfileDisplayer());
		TextAreaAppender appender = new TextAreaAppender();
		appender.setLayout(new PatternLayout());
		BasicConfigurator.configure(appender);
	}

	@Override
	public void actionPerformed(ActionEvent event)
	{		
		try
		{
			File logFile = workbench.getLogfileDirectoryFile();
			if(logFile != null)
			{
				Layout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN);
				try
                {
	                FileAppender fileAppender = new FileAppender(layout, logFile.getAbsolutePath(), true);
	                Logger.getRootLogger().addAppender(fileAppender);
                }
                catch(IOException e)
                {
                	JOptionPane.showMessageDialog(null, "Could not write to log file: " + e.getLocalizedMessage(), "Error while synchronizing", JOptionPane.ERROR_MESSAGE);
                }
			}
			
			
			final DirectorySynchronizer synchronizer = new DirectorySynchronizer(workbench.getMainFrame(), workbench.getSourceDirectoryFile(), workbench.getTargetDirectoryFile());
			workbench.setSynchronizer(synchronizer);
			


			SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>()
			{

				@Override
                protected Void doInBackground() throws Exception
                {
					workbench.getStartSynchronizingButton().setEnabled(false);
					workbench.getStopSynchronizingButton().setEnabled(true);
	                synchronizer.start();
	    			workbench.getStartSynchronizingButton().setEnabled(true);
	    			workbench.getStopSynchronizingButton().setEnabled(false);
	                return null;
	           
                }
				
			};
			
			worker.execute();
			


		}
		catch(DirectorySynchronizeException ex)
		{
			JOptionPane.showMessageDialog(null, ex.getLocalizedMessage(), "Error while synchronizing", JOptionPane.ERROR_MESSAGE);	
		}
		
	}
}
